package com.common.valid;



import com.common.Util.StringUtils;
import com.common.valid.annotation.DateFormat;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.SimpleDateFormat;

public class DateFormatValidator implements ConstraintValidator<DateFormat, Object> {
    private DateFormat dateFormat;

    @Override
    public void initialize(DateFormat dateFormat) {
        this.dateFormat = dateFormat;
    }

    @Override
    public boolean isValid(Object s, ConstraintValidatorContext constraintValidatorContext) {
        String format = StringUtils.getStringOrDefault(dateFormat.value(),dateFormat.format());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        try {
            simpleDateFormat.parse(String.valueOf(s));
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}